package influxdb

import (
	"github.com/influxdata/influxdb/client/v2"
	"log"
	"sync"
)

var (
	once    sync.Once
	connect Connect
)

/**
查询数据
*/
func (c *Connect) queryDB(cmd string) (res []client.Result, err error) {
	q := client.Query{
		Command:  cmd,
		Database: c.DbName,
	}
	if response, err := c.Client.Query(q); err == nil {
		if response.Error() != nil {
			return res, response.Error()
		}
		res = response.Results
	} else {
		return res, err
	}
	return res, nil
}

/**
插入数据
*/
func (c *Connect) insert(number int, point []*client.Point) int {
	if number <= 0 {
		number = 20000
	}
	cpointLen := len(point)
	result := 0
	if cpointLen > number {
		gCount := cpointLen / number
		for i := 0; i < gCount; i++ {
			result += c.cWriter(point[number*i : number*(i+1)])
		}
		result += c.cWriter(point[number*gCount : cpointLen])
		return result
	} else {
		return c.cWriter(point)
	}

	//bp.AddPoints(point)
	//err = c.Client.Write(bp)
	//if err != nil {
	//	log.Println(err)
	//	return -1
	//} else {
	//	return len(point)
	//}

}

func (c *Connect) cWriter(point []*client.Point) int {
	bp, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database: c.DbName,
	})
	if err != nil {
		log.Println(err)
	}
	bp.AddPoints(point)
	err = c.Client.Write(bp)
	if err != nil {
		log.Println(err)
		return -1
	} else {
		return len(point)
	}
}

type Connect struct {
	Addr     string
	UserName string
	Password string
	DbName   string
	TimeZone string
	Client   client.Client
}

func NewConnect(addr, userName, password, dbName, timeZone string) *Connect {
	once.Do(func() {
		connect = Connect{Addr: addr,
			UserName: userName,
			Password: password,
			DbName:   dbName,
			TimeZone: timeZone}

		client, err := client.NewHTTPClient(client.HTTPConfig{
			Addr:     connect.Addr,
			Username: connect.UserName,
			Password: connect.TimeZone,
		})
		if err != nil {
			//sysinit.LogError(err.Error())
			panic(err)
		} else {
			connect.Client = client
		}
	})
	return &connect
}
